local SQL           = require "sql"
local show          = require "showmsg" 

local account = {}

function account:create_AccountDB_SQL()

    local AccountDB_SQL = {

            manager = {},
            sql     = {},
    
            -- 全局 sql 设置 
            global_db_hostname = '',
            global_db_port = 0,
            global_db_username = '',
            global_db_password = '',
            global_db_database = '',

            -- 局部 sql 设置
            db_hostname = '',
            db_port = 0,
            db_username = '',
            db_password = '',
            db_database = '',
            case_sensitive = 0, -- 区分大小写
            account_db = '',    -- 账户数据表   
        }

        return AccountDB_SQL
end 

function account:db_sql()

    local AccountDB = self:create_AccountDB_SQL()
    
    -- 以下设置为默认值
    AccountDB.sql = false

    -- 全局 sql 设置
    AccountDB.global_db_hostname    = "127.0.0.1"
    AccountDB.global_db_port        = 3306
    AccountDB.global_db_username    = "root"
    AccountDB.global_db_password    = "123123"
    AccountDB.global_db_database    = "main"
    
    -- 局部 sql 设置
    AccountDB.db_hostname   = ''
    AccountDB.db_port       = 3306
    AccountDB.db_username   = ''
    AccountDB.db_password   = ''
    AccountDB.db_database   = ''
    
    -- 其他设置
    AccountDB.account_db = "login"

    return AccountDB
end 


function account:db_sql_init(this)

    
    local sql 
    local conf  = {}

    this.sql = self:db_sql()
    sql = this.sql

    if this.db_hostname ~= '' then 

        conf.host     = this.db_hostname
        conf.port     = this.db_port
        conf.basename = this.db_database
        conf.user     = this.db_username
        conf.pawd     = this.db_password 

    else 

        conf.host     = this.global_db_hostname
        conf.port     = this.global_db_port
        conf.basename = this.global_db_database
        conf.user     = this.global_db_username
        conf.pawd     = this.global_db_password

    end 


    if SQL_ERROR == SQL:connect_db(sql,conf) then 

        SQL:show_debug(sql, "account_sql.lua", "连接数据库失败")
        return false
    end

    show:info("连接到主数据库 %s", conf.basename) 

    return true 
end 

-- 如果支持该选项，则调整内部状态
function account:db_sql_set_property(this, key, value, size)

    local signature
    -- sql.
    -- account.sql.
    signature = "sql."
    
    if string.find(ni) then 
    end 
end 

function account:db_sql_get_property(this, key)
end 


function account:db_sql_create(this, acc)

    local sql = this.sql

    local account_id 

    if acc.account_id  ~= -1 then 
    
        account_id = acc.account_id
    else 
        -- 问数据库
        if SQL_ERROR == SQL:query(sql,"SELECT MAX(`account_id`)+1 FROM `%s`", this.account_db) then 
            SQL:show_debug(sql, "account_sql.lua -> account_db_sql_create", "查询语句错误")
           
            return false 
        end 

        if #sql.result <= 0 then 

            SQL:free_result(sql)
            return false 
        end 

        SQL:get_data(sql)

        account_id = tonumber(sql.data[1]) or 0
        
       if account_id < MAX_START_ACCOUNT_NUM then 

          account_id = MAX_START_ACCOUNT_NUM
       end  

    end 

    if account_id == 0 then 

        return false 
    end 

    if account_id > MAX_END_ACCOUNT_NUM then 
        return false 
    end 

    acc.account_id = account_id 

    return self:mmo_auth_tosql(this, acc, true )
end 


function account:db_sql_remove(this, account_id)

    local sql = this.sql 

    local result = false 

    if SQL_SUCCESS ~= SQL:query(sql, "START TRANSACTION") or
       SQL:query(sql, "DELETE FROM `%s` WHERE `account_id` = '%d'", this.account_db, account_id)  then 

        SQL:show_debug(sql, "account_sql.lua -> account_db_sql_remove", "删除语句错误")
    else 
        result = true 
    end 

    SQL:query((result and "commit") or "rollback")

    return result    
end 

-- 保存账户信息
function account:db_sql_save(this, acc)
    
    return self:mmo_auth_tosql(this, acc, false)
end
 
-- 加载账户信息
function account:db_sql_load_num(this, acc, account_id)

    return self:mmo_auth_fromsql(this, acc, account_id)
end 

function account:db_sql_load_str(this, acc, userid)

    local sql = this.sql 

    local account_id 

    -- 查询ID
    if SQL_ERROR == SQL:query(sql, "SELECT `account_id` FROM `%s` WHERE `userid` =  %s '%s'",
        this.account_db, (this.case_sensitive and "BINARY") or "" , userid) then 
        
        SQL:show_debug(sql, "account_sql.lua -> db_sql_load_str", "查询语句错误")
        return false 
    end  

    -- 如果存在多个
    if #sql.result > 1 then 
        
        show:error("db_sql_load_str: 在检索数据时发现多个帐户 %s", userid)
        SQL:free_result(sql)
        return false 
    end 

    --　如果该ID不存在
    if #sql.result == 0 then 

        SQL:free_result(sql)
        return false 
    end 

    SQL:get_data(sql) 

    account_id = tonumber(sql.data.account_id)

    return self:db_sql_load_num(this, acc, account_id)
end 

--数据库认证数据   db = AccountDB_SQL    mmo_account 
function account:mmo_auth_fromsql(db, acc, account_id)

    local sql = db.sql

    if SQL_ERROR == SQL:query(sql, "SELECT `account_id`, `userid`, `user_pass`，`sex`，`email`， `level` ，\
        `state`， `unban_time`， `expiration_time`， `logincount`， `lastlogin`，`last_ip`，`birthdate`，`vip_time` FROM `%s` where\
        `account_id` = '%d'", db.account_db, account_id) then 

        SQL:show_debug(sql, "account_sql.lua -> mmo_auth_fromsql", "查询语句错误")
        return false
    end 
    
    -- 检查是否有数据
    if #sql.result <= 0 then 
        return false 
    end  

    SQL:get_data(sql)

    acc.account_id      = sql.data.account_id
    acc.userid          = sql.data.userid
    acc.user_pass       = sql.data.user_pass
    acc.sex             = sql.data.sex
    acc.email           = sql.data.email
    acc.level           = sql.data.level
    acc.state           = sql.data.state
    acc.unban_time      = sql.data.unban_time
    acc.expiration_time = sql.data.expiration_time
    acc.logincount      = sql.data.logincount
    acc.lastlogin       = sql.data.lastlogin
    acc.last_ip         = sql.data.last_ip
    acc.birthdate       = sql.data.birthdate
    acc.vip_time        = sql.data.vip_time
    
    return true 
end 

function account:mmo_auth_tosql(db, acc, is_new)

    local result = false 

    local sql = db.sql

    repeat 

        if SQL_ERROR == SQL:query(sql,"START TRANSACTION") then 
            SQL:show_debug(sql, "account_sql.lua ","开始事物语句失败")
            break 
        end 

        if is_new then 

            if SQL_ERROR == SQL:query(sql, "INSERT INTO `%s`(`userid`, `user_pass`，`sex`，`email`，`level` ， `state`， `unban_time`， `expiration_time`， `logincount`， `lastlogin`，`last_ip`，`birthdate`，`vip_time`) \
                VALUE('%s','%s', '%s', '%s', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s')", 
                db.account_db, acc.userid, acc.user_pass, acc.sex, acc.email, acc.level, acc.unban_time, acc.expiration_time,
                acc.logincount, acc.last_ip, acc.birthdate, acc.vip_time) then 

                SQL:show_debug(sql, "account_sql.lua", "插入角色数据失败")
                break 
            end 

        else 

            if SQL_ERROR == SQL:query(sql, "UPDATE `%s` SET `userid`='%s', `user_pass`='%s', `sex`='%s', `email`='%s', `level`='%d', `stare`='%d', `unban_time`='%s', `logincount`='%d', `lastlogin`='%s', `last_ip`='%s', `birthdate`='%s', `vip_time`='%s' ",
                db.account_db, acc.userid, acc.user_pass, acc.sex, acc.email, acc.level, acc.unban_time, acc.expiration_time,
                acc.logincount, acc.last_ip, acc.birthdate, acc.vip_time) then   

                SQL:show_debug(sql, "account_sql.lua", "插入角色数据失败")
                break 
            end 

        end 

        -- 如果我们到目前为止，一切都是成功
        result =  true 

    until( true )

    SQL:query((result and "commit") or "rollback")

    return result
end 

--获取数据
function account:db_sql()

    local sql = SQL:new_sql_handler()
    return sql
end 


--断开与数据库的连接
function account:db_sql_destroy(this)
    
    SQL:close_db(this.sql)
    this.sql = nil
end 

function account:init_connect(fd)

    
end 

return account